//
//  KHBaseViewController.m
//  KissHealth
//
//  Created by Mark on 2017/1/11.
//  Copyright © 2017年 Mark. All rights reserved.
//

#import "KHBaseViewController.h"
#import "WebViewJavascriptBridge.h"
#import "KHCustomTool.h"
#import "KHCommentVC.h"
#import "KHTabBarViewController.h"
#import "KHConsultVC.h"
#import "KHPhotoBrowserController.h"
#import "TZImagePickerController.h"
#import "NSURLProtocolCustom.h"
#import "KHImageTool.h"
#import "UIWebView+JavaScriptAlert.h"
#import "NSURLRequest+IgnoreSSL.h"
#import "KHBlueToothManager.h"

@interface KHBaseViewController ()<UIWebViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate>

@property (nonatomic,weak)UIButton *maskNoNetwork;
@property (nonatomic,copy)NSString *urlStr;

@property(nonatomic,assign) BOOL showCamora;
@property(nonatomic,assign) NSInteger count;

@end

@implementation KHBaseViewController

- (instancetype)initWithURL:(NSString *)urlStr{
    self  = [super init];
    if (self) {
        self.urlStr = urlStr;
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self becomeActive:nil];
}

- (void)viewDidDisappear:(BOOL)animated{
    [self enterBackground:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 这里可以看出 只要注册一次就够了。。。我们可以将它写在delegate 入口就可以实现所有的请求拦截
    [NSURLProtocol registerClass:[NSURLProtocolCustom class]];

    // 1.webView
    UIWebView *webView = [[UIWebView alloc] init];
    webView.backgroundColor = [UIColor whiteColor];
    webView.frame = self.view.bounds;
    webView.delegate = self;
//    webView.scalesPageToFit = YES;
//    webView.opaque = NO;
    // 2.加载网页
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]];
    [webView loadRequest:request];
    [self.view addSubview:webView];
    self.webView = webView;
    
    
    //3.mask
    UIButton *maskNoNetwork = [UIButton buttonWithType:UIButtonTypeCustom];
    [maskNoNetwork setImage:[UIImage imageNamed:@"load_failed"] forState:UIControlStateNormal];
    maskNoNetwork.backgroundColor = [UIColor whiteColor];
    [maskNoNetwork addTarget:self action:@selector(onClicked:) forControlEvents:UIControlEventTouchUpInside];
    maskNoNetwork.frame = CGRectMake(0, 64, kSCREEN_W, kSCREEN_H - 64);
    maskNoNetwork.hidden = YES;
    [self.view addSubview:maskNoNetwork];
    self.maskNoNetwork = maskNoNetwork;
    
    [self observeEnterBackgroundOrBecomeActive];
    
    [self addCustomActions];

    
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark - private
- (void)observeEnterBackgroundOrBecomeActive{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive:)name:UIApplicationDidBecomeActiveNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterBackground:)name:UIApplicationDidEnterBackgroundNotification object:nil];
    
}

//由后台到前台oc会自动调用js函数onResume
- (void)becomeActive:(NSNotification *)noti{
    JSValue *function = self.context[@"onResume"];
    //JSValue *result = [function callWithArguments:nil]; 无返回值所以直接如下写法
    [function callWithArguments:nil];
}

//由前台到后台会自动调用js函数onPause
- (void)enterBackground:(NSNotification *)noti{
    JSValue *function = self.context[@"onPause"];
    [function callWithArguments:nil];
}


// 在webViewDidFinishLoad 加载完 context 才会有值
- (void)addCustomActions{
    
    __block typeof(self) weakSelf = self;
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.context = context;
    context[@"alert"] = ^() {
        NSArray *args = [JSContext currentArguments];
        NSString *url = [args[0] toString];
        
        
    };

    

    // JS主动调用OjbC的方法
    //{"url":url,"finish":finish,"param":param}
    //[url,finish,param]
    context[@"startBaseActivity"] = ^() {
        NSArray *args = [JSContext currentArguments];
        NSString *url = [args[0] toString];
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            KHCommentVC *commetVC = [[KHCommentVC alloc]initWithURL:url];
            [weakSelf.navigationController pushViewController:commetVC animated:YES];
        });

 
    };
    
    // {"activity":activity,"url":url,"finish":finish,"param":param}
    //param {“indexInUrls”:1, “urls”:[”url1”, “url2”, “url3”]}
    context[@"startActivity"] = ^() {
        NSArray *args = [JSContext currentArguments];
        NSString *vcClass = [args[0] toString];
        NSString *url = [args[1] toString];
        BOOL finish = [args[2] toBool];
        NSString *paramStr = [args[3] toString];
        NSDictionary *param = [NSString parseJSONStringToNSDictionary:paramStr];
            if ([vcClass isEqualToString:@"KHTabBarViewController"]) {
                NSArray *urls = [param objectForKey:@"urls"];
                
                //loginedUrl 这个主要是用于推送未登录时的URL
                NSString *loginedUrl = [param objectForKey:@"loginedUrl"];
                if (loginedUrl ==nil || [loginedUrl isEqualToString:@"null"]) {
                    loginedUrl = @"";
                }
                dispatch_async(dispatch_get_main_queue(), ^{

                    UIWindow *window = [UIApplication sharedApplication].keyWindow;
                    if (finish) {
                        window.rootViewController = nil;
                    }
                    window.rootViewController = [[KHTabBarViewController alloc]initWithURLStrings:urls withLoginedUrl:loginedUrl];
                });

                
            }else if ([vcClass isEqualToString:@"KHConsultVC"]){
                dispatch_async(dispatch_get_main_queue(), ^{

                    KHConsultVC *consultVC = [[KHConsultVC alloc]initWithURL:url];
                    [self.navigationController pushViewController:consultVC animated:YES];
                });

                
            }else if ([vcClass isEqualToString:@"KHPhotosVC"]){
                
                NSInteger index = [[param objectForKey:@"indexInUrls"] intValue];
                NSArray *urls = [param objectForKey:@"urls"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    KHPhotoBrowserController *photoVC = [[KHPhotoBrowserController alloc]init];
                    photoVC.index = index;
                    photoVC.picURLs = urls;
                    [self presentViewController:photoVC animated:YES completion:^{
                    }];
                });
            }
    };

    
    context[@"FinishActivity"] = ^() {
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            [KHCustomTool finishActivity];
        });

    };

    //[toast]
    context[@"showToast"] = ^() {
        NSArray *args = [JSContext currentArguments];
        NSString *toast = [args[0] toString];
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            [KHCustomTool showToast:toast];
        });

    };


    //{"key":key,"value":value}
    //[key,value]
    context[@"setValue"] = ^() {
        NSArray *args = [JSContext currentArguments];
        NSString *key = [args[0] toString];
        NSString *value = [args[1] toString];
        [KHCustomTool setValue:value key:key];

    };

    //[key]
    context[@"removeValue"] = ^() {
        NSArray *args = [JSContext currentArguments];
        NSString *key = [args[0] toString];
        [KHCustomTool removeValue:key];
    };

    context[@"quitApp"] = ^() {
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            [KHCustomTool quitApp];

        });

    };

    
    //[url]
    context[@"startWebSite"] = ^() {
        NSArray *args = [JSContext currentArguments];
        NSString *url = [args[0] toString];
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            [KHCustomTool startWebSite:url];
            
        });

    };
    
    context[@"reload"] = ^() {
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            [weakSelf.webView reload];
            
        });

    };
    
    //还有一个更改头像图片 刷新
    //[index,param]
    context[@"showFragment"] = ^() {
        NSArray *args = [JSContext currentArguments];
        int index  = [args[0] toInt32];
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            [KHCustomTool showFragment:index];
            
        });
    };
    
    context[@"cleanCache"] = ^() {
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            [KHCustomTool cleanCache];
            
        });

    };
    
    
    //[tag,msg]
    context[@"logD"] = ^() {
        NSArray *args = [JSContext currentArguments];
        NSString *tag  = [args[0] toString];
        NSString *msg  = [args[1] toString];
        NSLog(@"tag:%@ msg:%@",tag,msg);

    };

    context[@"logI"] = ^() {
        NSArray *args = [JSContext currentArguments];
        NSString *tag  = [args[0] toString];
        NSString *msg  = [args[1] toString];
        NSLog(@"tag:%@ msg:%@",tag,msg);
        
    };
    
    context[@"logW"] = ^() {
        NSArray *args = [JSContext currentArguments];
        NSString *tag  = [args[0] toString];
        NSString *msg  = [args[1] toString];
        NSLog(@"tag:%@ msg:%@",tag,msg);
        
    };
    
    context[@"logE"] = ^() {
        NSArray *args = [JSContext currentArguments];
        NSString *tag  = [args[0] toString];
        NSString *msg  = [args[1] toString];
        NSLog(@"tag:%@ msg:%@",tag,msg);
        
    };
    
    //[showCamora,count]
    context[@"startSelectPhotoActivity"] = ^() {
        NSArray *args = [JSContext currentArguments];
        BOOL showCamora  = [args[0] toBool];
        NSInteger count  = [args[1] toInt32];
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            [weakSelf startSelectPhotoActivityShowCamora:showCamora withCount:count];
            
        });

        
    };

    context[@"fileToBase64"] = ^() {
        NSArray *args = [JSContext currentArguments];
        NSString *path  = [args[0] toString];
        //根据这个路径拿到base64
        NSString *base64Str = [KHCustomTool getValue:path];
        return base64Str;
    };

    
    context[@"getValue"] = ^() {
        NSArray *args = [JSContext currentArguments];
        NSString *key  = [args[0] toString];
        NSString *value = [KHCustomTool getValue:key];
        return value;
    };

    
    context[@"getDeviceUniqueId"] = ^() {

        return [KHCustomTool getDeviceUniqueId];
    };

    
    context[@"getPushId"] = ^() {
          return [KHCustomTool getPushId];
    };

    
    context[@"getVersion"] = ^() {
        return [KHCustomTool getVersion];
    };

   
    context[@"getNetState"] = ^() {
        return [KHCustomTool getNetState];
    };
    
    
#pragma mark - 蓝牙设备连接
    context[@"startTestAll"] = ^() {
        NSArray *args = [JSContext currentArguments];
        if (args.count < 2) return;
        NSString *dictString = [[args objectAtIndex:1] toString];
        NSData *data = [dictString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSString *key = [[dict allKeys] firstObject];
        NSString *method = [dict valueForKey:key];
        
        KHPeripheralType type = [KHBlueToothHelper peripheralTypeForMeter:key];
        [[KHBlueToothManager sharedManager] beginBlueToothMeterWithType:type block:^(NSString * _Nonnull passedValue) {
            JSValue *function = self.context[method];
            [function callWithArguments:@[passedValue]];
        }];
    
    };
    
    context[@"startTest"] = ^() {
        NSArray *args = [JSContext currentArguments];
        NSLog(@"%@", args);
    };
    
    context[@"stopTest"] = ^() {
        // 停止扫描和设备连接
        [[KHBlueToothManager sharedManager] stopPeripheralsConnection];
    };
}


#pragma mark - UIWebviewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"%@", request.URL.absoluteString);
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // 禁用选中效果
    [self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none'"];
    [self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none'"];
    
    //js 调用oc
    [self addCustomActions];
    if ([webView.request.URL.absoluteString isEqualToString:kLoginURLString]) {
        NSString *value = [KHCustomTool getValue:@"autoLoginCheck"];
        if ([value isEqualToString:@"1"]) {
            JSValue *function = self.context[@"audoLogin"];
            [function callWithArguments:nil];

        }
    }

    [SVProgressHUD dismiss];

}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"%@",webView.request.URL.absoluteString);
    [SVProgressHUD showWithStatus:@"正在加载"];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
}


- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [SVProgressHUD dismiss];
    if ([KHCustomTool getNetState] == -1) {
        self.maskNoNetwork.hidden = NO;
    }else{
        self.maskNoNetwork.hidden = YES;
    }
}


#pragma mark - UIImagePickerControllerDelegate
/**
 * 从UIImagePickerController选择完图片后就调用（拍照完毕或者选择相册图片完毕）
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    // info中就包含了选择的图片
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    NSString *base64String = [KHImageTool base64StingWithImage:image];
    NSString *mimeType = [KHImageTool mimeTypeWithImage:image];
    
    //{"urls" : ["url1", "url2", "url3"];
    //获取毫秒的时间戳
    UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
    NSString *recordStr = [NSString stringWithFormat:@"%llu",recordTime];
    NSString *urlStr = [NSString stringWithFormat:@"local://cameraPhotoImage_%@%@",recordStr,mimeType];
    [KHCustomTool setValue:base64String key:urlStr];
    
    //解决调用js 弹框卡的问题
    [self performSelectorOnMainThread:@selector(callJS:) withObject:@[urlStr] waitUntilDone:NO];

//    [self callJS:@[urlStr]];
    
    //图片上传成功 更改成功的话 发通知
    [[NSNotificationCenter defaultCenter]postNotificationName:kPhotoImageChangeNotification object:self];
    
}

/**
 * 回调选择图片操作
 // ViewSendFiles {"urls" : ["url1", "url2", "url3"];
 ["url1", "url2", "url3"]
 */

- (void)callJS:(NSArray *)tempArray{
    //NSString *str = [tempArray componentsJoinedByString:@","];
    //转成json 字符串
    
    NSString *photoKey = tempArray.firstObject;
      [KHCustomTool getValue:photoKey];
    
    NSData *data=[NSJSONSerialization dataWithJSONObject:tempArray options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    JSValue *function = self.context[@"callBackPic"];
    [function callWithArguments:@[jsonStr]];
    
    
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}


#pragma mark -  camera private
- (void)showCamera:(BOOL)showCamera withCount:(NSInteger)count{
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera];
    }];
    
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openAlbum];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    if (showCamera) [alertVC addAction:cameraAction];
    [alertVC addAction:photoAction];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
    
}

- (void)openCamera
{
    [self openImagePickerController:UIImagePickerControllerSourceTypeCamera];
}

- (void)openAlbum
{
    __block typeof(self) weakSelf = self;
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.count delegate:self];
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowTakePicture = NO;
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL success) {
        //{"urls" : ["url1", "url2", "url3"];
        NSMutableArray *tempArray = [NSMutableArray array];
        for (int i = 0; i<photos.count; i++) {
            UIImage *image = photos[i];
            
            NSString *base64String = [KHImageTool base64StingWithImage:image];
            NSString *mimeType = [KHImageTool mimeTypeWithImage:image];
            
            //获取毫秒的时间戳
            UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
            NSString *recordStr = [NSString stringWithFormat:@"%llu",recordTime];
            NSString *urlStr = [NSString stringWithFormat:@"local://photoImage_%drecord%@%@",i,recordStr,mimeType];
            [KHCustomTool setValue:base64String key:urlStr];
            [tempArray addObject:urlStr];
            
        }
     [weakSelf performSelectorOnMainThread:@selector(callJS:) withObject:tempArray waitUntilDone:NO];

//        [weakSelf callJS:tempArray];
     
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}


- (void)openImagePickerController:(UIImagePickerControllerSourceType)type
{
    if (![UIImagePickerController isSourceTypeAvailable:type]) return;
    
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = type;
    ipc.delegate = self;
    
    [self presentViewController:ipc animated:YES completion:nil];
}

- (void )startSelectPhotoActivityShowCamora:(BOOL)showCamora withCount:(NSInteger)count{
    self.showCamora = showCamora;
    self.count = count;
    [self showCamera:self.showCamora withCount:self.count];
    
}

- (void)onClicked:(UIButton *)sender{
    self.maskNoNetwork.hidden = YES;
    [self.webView reload];
}


@end
